<template>
    <div class="card-page">
        <tool-bar nav="" :title="action_name + '集群'">
            <el-button @click="vue_configmap_click()" v-if="$props.action=='edit'">同步生成 nginxconf 中的 web.conf</el-button>
<!--            <el-button @click="$data.dlg_show= true;">全局修改nacos配置</el-button>-->
            <el-button size="small" @click="$router.push('/dev/cluster-info/add')" v-if="$props.action=='edit'">新建</el-button>
            <el-button size="small" @click="save_click" type="primary">保存</el-button>
        </tool-bar>
        <el-row :gutter="12" type="flex">
            <el-col style="flex:4">
                <el-card shadow="always">

                    <template #header><span>基本信息</span></template>
                    <kv label="序号">
                        <el-input v-model="info.index" chk="?int"/>
                    </kv>
                    <kv label="访问端口号">
                        <el-tag>{{ info.index || 800 }}</el-tag>
                    </kv>
                    <kv label="编码(k8s名称空间)">
                        <el-input v-model="info.code"
                                  chk=": if( value.replace(/[\w\d-]/ig, '').length) return '必须是连字符格式' "/>
                    </kv>
                    <kv label="名称">
                        <el-input v-model="info.name" chk="*"/>
                    </kv>
                    <kv label="备注">
                        <el-input v-model="info.remark" type="textarea"/>
                    </kv>
                </el-card>
            </el-col>
            <el-col style="flex:6;" v-if="info.id">
                <el-card shadow="always">
                    <template #header> <div>
                        当前环境:
                        <!--                            <app-env v-model="targetEnv" @change="targetEnv_change" @proc="proc_data"-->
                        <!--                                     style="display: inline-block"></app-env>-->
                        <div v-if="$data.currentSetting?.code"
                             style="display: inline-block;margin-left:8px;">
                            <el-tag>{{ $data.currentSetting.code }}</el-tag>
                            流水线：{{ $data.currentSetting.pipelineTemplate_res }},
                            集群：{{ $data.currentSetting.clusterDeployEnv }}
                        </div>
                    </div> </template>

                    <ul>
                        <li class="row">
                            <el-button @click="e=>post_i_url('/ops/k8s/service/create-ns?namespace=' + info.code,e)">
                                创建K8s名称空间 {{ info.code }}
                            </el-button>

                            <el-button
                                @click="e=> post_i_url('/ops/k8s/service/set-ns-configmap-role?namespace='+ info.code,e )">
                                设置名称空间{{ info.code }} configmap读取权限
                            </el-button>


                        </li>
                        <li class="row">
                            <label>endpoint</label>
                            <el-input style="width:50%;min-width:200px;" v-model="$data.sourceNamespace">
                                <template slot="prepend">参考源名称空间</template>
                            </el-input>
                            <input-table style="width:100%"
                                         v-model="$data.endpoints" @add="v=>{  }">
                                <el-table-column align="center" label="名称">
                                    <template v-slot="scope">
                                        <el-input v-model="scope.row.name"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="端口号">
                                    <template v-slot="scope">
                                        <el-input v-model="scope.row.port"></el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column align="center" label="应用">
                                    <template v-slot="scope">
                                        <el-button :disabled="!scope.row.name || !scope.row.port"
                                                   style="margin-left:8px;"
                                                   @click="e=> post_i_url('/ops/k8s/service/deploy-endpoint?name='  + scope.row.name +'&namespace='+ info.code  +'&port=' + scope.row.port + '&sourceNamespace=' + sourceNamespace,e )">
                                            添加！
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </input-table>
                        </li>

                        <li class="row">
                            <label>external-name</label>

                            <input-table style="width:100%"
                                         v-model="$data.externals" @add="v=>{  }">
                                <el-table-column align="center" label="名称">
                                    <template v-slot="scope">
                                        <el-input v-model="scope.row.name"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="应用">
                                    <template v-slot="scope">
                                        <el-button :disabled="!scope.row.name"
                                                   style="margin-left:8px;"
                                                   @click="e=> post_i_url('/ops/k8s/service/deploy-external?name='  + scope.row.name +'&namespace='+ info.code  +'&sourceName=' + scope.row.name + '&sourceNamespace=' + sourceNamespace,e )">
                                            添加！
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </input-table>
                        </li>

                        <li class="row">

                            <el-button
                                @click="e=> post_i_url('/ops/k8s/service/deploy-nginx?namespace='+ info.code,e )">
                                部署
                                nginx
                            </el-button>
                            包含nginxconf configmap,deployment,service
                            <br/>
                            <el-button
                                @click="e=> post_i_url('/ops/k8s/service/restart?namespace='+ info.code + '&serviceName=nginx',e )">
                                重启Nginx
                            </el-button>
                        </li>


                        <li class="row">

                            <el-button
                                @click="e=> post_i_url('/ops/k8s/service/deploy-gateway?namespace='+ info.code,e)">
                                部署 一级网关 {{ info.code }}-gateway-api-java
                            </el-button>
                            要求 mp 下已手动部署了 mp-gateway-api-java
                        </li>


                        <li class="row">
                            访问其它k8s名称空间
                            <el-input v-model="$data.connect_ns" style="display: inline-block;width:120px;"></el-input>

                            <div v-if="$data.connect_ns">
                                <el-button
                                    @click="e=> post_i_url('/ops/k8s/service/deploy-external?namespace='+ info.code + '&name=' + $data.connect_ns +'-api&sourceNamespace=' + $data.connect_ns + '&sourceName=' + $data.connect_ns + '-gateway-api-java',e)">
                                    部署 {{ $data.connect_ns }}-api
                                </el-button>
                                <span>，指向 {{ $data.connect_ns }}.{{ $data.connect_ns }}-gateway-api-java， 可以访问 <el-tag>{{
                                        $data.connect_ns
                                    }}</el-tag> 名称空间下的所有的微服务</span>

                                <div>
                                    测试，在当前名称空间下，执行:
                                    <el-tag>curl http://{{ $data.connect_ns }}-api/hi</el-tag>
                                </div>
                            </div>
                        </li>



                        <li class="row">
                            <el-button
                                @click="e=> post_i_url('/ops/k8s/configmap/set-nginx-configmap?namespace='+ info.code,e)">
                                同步
                                nginx
                                configmap
                            </el-button>
                            把已部署的前后端服务，更新到 configmap 中。
                        </li>
                        <li class="row">
                            <input-table style="width:100%"
                                         v-model="$data.currentSetting.containerMemories" :buttons="false">
                                <el-table-column align="center" label="语言" minWidth="60">
                                    <template v-slot="scope">
                                        <el-tag>{{ scope.row.language }}</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="最大内存(Mi)" minWidth="120">
                                    <template v-slot="scope">
                                        <span v-html="scope.row.max"/>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="初始内存(Mi)" minWidth="120">
                                    <template v-slot="scope">
                                        <span v-html="scope.row.request"/>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="匹量设置" minWidth="80">
                                    <template v-slot="scope">
                                        <el-button @click="set_memory(scope.row)">匹量设置</el-button>
                                    </template>
                                </el-table-column>
                            </input-table>
                        </li>
                    </ul>
                </el-card>


            </el-col>
        </el-row>

        <el-dialog v-model="$data.dlg_show" title="设置Nacos" ref="dlg">
            <kv label="名称空间">
                <div>{{ info.code }}</div>
            </kv>
            <kv label="dataId">
                <el-input v-model="info.name"></el-input>
            </kv>
            <kv label="属性">
                <el-input v-model="info.key" chk="*"></el-input>
            </kv>
            <kv label="值">
                <el-input v-model="info.value" chk="*"></el-input>
            </kv>

            <kv label="选项">
                <selector v-model="info.option" chk="*"
                          :data="{'exists':'存在才设置','all':'所有配置文件设置值'}"></selector>
            </kv>
            <el-button @click="config_nacos_click">设置</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
/**
 * Created by CodeGenerator  at 2022-06-09 16:14:59
 */

import appEnv from "@/component/app-env.vue";



//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs()


//定义事件
const $emit = defineEmits(["update:modelValue", "loaded"]);

//定义属性
const $props = defineProps({
    id: {type: String, default: ""},
    action: {type: String, default: ""}
});

const action_name = $computed(() => {
    return {add: "添加", edit: "修改"}[$props.action]
})

//定义data
const $data = reactive({
    sourceNamespace: "default",
    targetEnv_changed: false,
    targetEnv: "",
    version: 0,
    currentSetting: {},
    info: {}, //子对象需要声明。
    connect_ns: "",
    dlg_show: false,
    // ext_services: "",
    endpoints: [{name: "mariadb", port: 3306}, {name: "mongo", port: 27017}, {name: "es", port: 9200}],
    externals: [{name: "redis"}, {name: "rabbitmq"}],

    external_name: "",
})

const info = $computed(()=>$data.info);


//定义 onMounted 方法
onMounted(() => {
    loadData()
    load_setting();
});

const vue_configmap_click = async function () {
  await jv.$http.post("/ops/k8s/configmap/set-nginx-configmap/" + info.code)
  jv.alert("设置并重启成功")
};

//定义 方法
const proc_data = function (data) {
    data.removeItem(it => !it.url);
}
const targetEnv_change = function (v, m, p) {
    load_setting();
}

const load_setting = function () {
    jv.targetEnv = $data.targetEnv;
    var url = "/dev/app-deploy-setting/detail?code=" + ($data.targetEnv || "");
    jv.$http.get(url).then(res => {
        $data.currentSetting = res.data.data;
        $data.currentSetting.pipelineTemplate_res = "";
        $data.currentSetting.clusterDeployEnv_res = "";

        if ($data.currentSetting.pipelineTemplate) {
            $data.currentSetting.pipelineTemplate_res = jv.enum.PipelineTemplateEnum.getData($data.currentSetting.pipelineTemplate).remark;
        }
        if ($data.currentSetting.clusterDeployEnv) {
            $data.currentSetting.clusterDeployEnv_res = jv.enum.MicroServiceDeployEnvEnum.getData($data.currentSetting.clusterDeployEnv).remark;
        }

        $data.version++;
    })
}

const post_i_url = async function (url, e, store) {
    if (store) {
        //jv.$saveData(store)
    }

    var res = await jv.$http.post(url, {targetEnv: $data.targetEnv});

    jv.info(e.target.innerText + " 成功")
}

const config_nacos_click = async function () {

    var url = "/ops/nacos/config/set-all"
    var p = Object.assign({}, $data.info, {namespace: $data.dlg_row.code});

    await jv.$http.post(url, p)

    jv.info($data.dlg_row.code + " 设置完成!")
}

const loadData = async function () {
    if (!$props.id) return;
    var res = await jv.$http.post("/dev/cluster-info/detail/" + $props.id)
    $data.info = res.data.data;
}
const save_click = async function () {
    //校验


    var res = await jv.$http.post("/dev/cluster-info/save", $data.info)
    //[axios拦截器中已处理了异常]。
    jv.info(action_name + " 成功");
    if ($props.action == "add") {
        var id = res.data.data
        // jv.setLastRowId("/dev/cluster-info/list", "list", id);
        jv.$router.push("/dev/cluster-info/edit/" + id)
    } else if ($props.action == "edit") {
        jv.$router.push("/dev/cluster-info/list")
    }
}
const set_memory = async function (row) {
    var res = await jv.$http.post("/ops/k8s/deployment/set-k8s-memory", {
        targetEnv: this.currentSetting.code,
        language: row.language,
        namespace: $data.info.code,
        max: row.max,
        request: row.request
    });
}

</script>
<style scoped lang="scss">

ul {
    list-style: none;
    list-style-type: none;
    counter-reset: sectioncounter;


    li.row {
        margin-bottom: 12px;
        border: solid 1px #a3c0ca;
        background-color: #f3fbfe;
        padding: 8px;
        border-radius: 4px;
        position: relative;

        label {
            position: absolute;
            z-index: 999;
            background-color: #c4ebee;
            top: -6px;
            padding: 2px 8px;
            border-radius: 10px;
            right: 16px;
        }
    }

    li:before {
        content: counter(sectioncounter);
        counter-increment: sectioncounter;
        font-weight: bold;
        color: white;
        font-family: HelveticaNeue-Bold, HelveticaNeue;
        position: absolute;
        right: -8px;
        top: -2px;
        background: #fa9914;
        width: 20px;
        height: 20px;
        border-radius: 18px;
        text-align: center;
        z-index: 999;
    }
}
</style>